package cn.kmsoft.spatialboot.controller;


import cn.kmsoft.common.RestResponse;
import cn.kmsoft.common.exception.ExceptionMsg;
import cn.kmsoft.common.exception.ServiceException;
import cn.kmsoft.spatialboot.config.DbConfig;
import cn.kmsoft.spatialboot.config.JdbcConfig;
import cn.kmsoft.wololo.object.GeoJson;
import cn.kmsoft.wololo.object.query.AnalysisType;
import cn.kmsoft.wololo.object.query.GeoJsonQuery;
import com.alibaba.fastjson.JSON;
import cn.kmsoft.spatialboot.service.SpatialAnalysisService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutionException;

import static org.springframework.util.MimeTypeUtils.APPLICATION_JSON_VALUE;



/**
 * @author
 * @date 2019/8/4.
 */
@CrossOrigin
@RestController
@Api(description = "空间查询", tags = "2.Spatial Query")
@RequestMapping(produces = APPLICATION_JSON_VALUE)
public class SpatialQueryController {

    private static final Logger logger = LoggerFactory.getLogger(SpatialQueryController.class);
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss-SSS");
    private final SpatialAnalysisService spatialAnalysisService;

    //@Autowired
    //private Map<String, DBConfig> dynamicDBConfig;
    @Autowired
    private DbConfig dbConfig;


    @Autowired
    public SpatialQueryController(SpatialAnalysisService spatialAnalysisService) {
        this.spatialAnalysisService = spatialAnalysisService;
    }

    @ApiOperation(value = "空间查询，以输入图形做面与面的空间套合查询,数据转换到fgeo_wkid投影下")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "instanceName", value = "数据库连接实例名,例如zyk_dbfgc", paramType = "path", required = true),
            @ApiImplicitParam(name = "tableId", value = "表ID，带表空间名。例如sde.bgdc_dltb_gjxfb_2022", paramType = "path", required = true),
            @ApiImplicitParam(name = "query", value = "geoJson叠加分析查询对象", paramType = "body", required = true, dataType = "GeoJsonQuery")
    })
    @PostMapping(value = "/spatialQuery2/{instanceName}/{tableId:.*}")
    public RestResponse spatialQueryPYByGeoJsonWithCrsTransform(@PathVariable String instanceName,
                                                                @PathVariable String tableId,
                                                                @RequestBody GeoJsonQuery query)
            throws ExecutionException, InterruptedException {
        System.out.println();
        String beginTime = sdf.format(new Date());
        System.out.println("*******************提交处理请求*******************," + beginTime);
        Integer wkid = query.getWkid();
        Integer fgeo_wkid = query.getFgeo_wkid();
        String geoJsonStr = query.getGeoJson();
        GeoJson geoJson = JSON.parseObject(geoJsonStr, GeoJson.class);

        //DBConfig dbConfig = dynamicDBConfig.get(instanceName);
        //String dbTypeName = dbConfig.getDbTypeName();
        JdbcConfig jdbcConfig= dbConfig.getJdbcCconfigByDbKey(instanceName);
        String dbTypeName = jdbcConfig.getDbtypename();

        if (query.getGeoJson().trim().startsWith("{")) {
            if (query.getDigits() == null) {
                query.setDigits(2);
            }
            if (AnalysisType.SPATIALQUERY.equals(query.getType())) {
                return RestResponse.succeed(
                        spatialAnalysisService.spatialQueryByGeoJson(dbTypeName, instanceName, tableId, query, "py2"));

            }
        }

        throw new ServiceException(ExceptionMsg.CLIENT_ERROR, "the format of geoJson is invalid");
    }


    @ApiOperation(value = "空间查询，以输入图形做面与面的空间套合查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "instanceName", value = "数据库连接实例名，例如zyk_dbfgc", paramType = "path", required = true),
            @ApiImplicitParam(name = "tableId", value = "表ID，带表空间名。例如sde.bgdc_dltb_gjxfb_2022", paramType = "path", required = true),
            @ApiImplicitParam(name = "query", value = "geoJson叠加分析查询对象", paramType = "body", required = true, dataType = "GeoJsonQuery")
    })
    @PostMapping(value = "/spatialQuery/{instanceName}/{tableId:.*}")
    public RestResponse spatialQueryPYByGeoJson(@PathVariable String instanceName, @PathVariable String tableId, @RequestBody GeoJsonQuery query)
            throws ExecutionException, InterruptedException {
        System.out.println();
        String beginTime = sdf.format(new Date());
        System.out.println("*******************提交处理请求*******************," + beginTime);

        JdbcConfig jdbcConfig= dbConfig.getJdbcCconfigByDbKey(instanceName);
        String dbTypeName = jdbcConfig.getDbtypename();

        if (query.getGeoJson().trim().startsWith("{")) {
            if (query.getDigits() == null) {
                query.setDigits(2);
            }
            if (AnalysisType.SPATIALQUERY.equals(query.getType())) {
                return RestResponse.succeed(
                        spatialAnalysisService.spatialQueryByGeoJson(dbTypeName, instanceName, tableId, query, "py"));

            }
        }

        throw new ServiceException(ExceptionMsg.CLIENT_ERROR, "the format of GeoJson is invalid");
    }

}
